global root_dir = "`1'"

include "$root_dir/code/config/config.do"

cap noi log using ${log_dir}/Figure_A3_montecarlo_p_histograms.log, replace name(fig)

capture noi {

    * --------------------------------------------- *
    *	Maintext: country + firmweight domestic     *
    * --------------------------------------------- *
    *TODO: the original estimates file... not clear where that comes from. depending on that we should put it somewhere else....
    clear

    cap program drop make_hist
    program make_hist
        local pversf "`1'"
        local n `2'
        local col `3'
        local title "`4'"
        local subtitle "`5'"
        if `col' != 2 {
            local noyaxis yscale(lstyle(none))
            local ytitle ytitle("")
            local ylab ylab(none)
        }
        else {
            local noyaxis ""
            local ytitle ytitle("Frequency")
            local ylab ylab(#3,nogrid)
        }


        local og_estimates_file "original_estimates.csv"

        local xtitle "xtitle("w{subscript:L} coefficient")"
        import delimited "${dataset_dir}/montecarlo/`og_estimates_file'", /// 
            clear varnames(1) case(preserve)
        qui sum estimateL if column==`col'
        local estimate_og =`r(mean)'
        local estimate_og_r = `estimate_og' * 4
        local estimate_og_r = round(`estimate_og_r', 1)
        local estimate_og_r = (`estimate_og_r' / 4)
        local estimate_og_r4: di (`estimate_og' / 4)
        di "Original estimate: `estimate_og'; rounded: `estimate_og_r'"

        use "${dataset_dir}/montecarlo/storage_runs_`pversf'_`n'", clear
        qui include ${code_dir}/config/figuretools.do
        local histaes "lcolor(white) lwidth(0.15pt) width(0.25) color(gs7) freq"
        *if bracket is a decidedly inelegant solution, but macros are just to annoying to handle
        if  "`cl'" == "" {
            tw (hist beta_L_`col' if beta_L_`col' < `estimate_og_r' &  beta_L_`col' > -6, start(-6) `histaes') ///
            (hist beta_L_`col' if beta_L_`col' >= `estimate_og_r' & beta_L_`col', /// 
            `histaes' start(`estimate_og_r') fcolor("`crm6'")), ///
            xline(`estimate_og', lpat(dash) lcol("`crm6'") lw(0.3)) ///
            `ytitle' `xtitle' ///
            xlabel(-6 -4 -2 0 2 4 6) xscale(range(-6 6) `xgap') ///
            `ylab' xlab(,nogrid) `noyaxis' title("`title'" "`subtitle'", position(6)) ///
            plotregion(margin(b=0 l=0)) ///
            name(`pversf'_col`col', replace)
        } 

    end program

    * output main text graph
    make_hist country 4000 2 "(A)  Country permutation" "Column 2"
    make_hist country 4000 5  "(B)  Country permutation" "Column 5"
    make_hist country 4000 8  "(C)  Country permutation" "Column 8"
    make_hist firmweightdomestic 4000 2 "(D)  Firm-weight permutation" "Column 2"
    make_hist firmweightdomestic 4000 5 "(E)  Firm-weight permutation" "Column 5"
    make_hist firmweightdomestic 4000 8 "(F)  Firm-weight permutation" "Column 8"

    grc1leg2 country_col2 country_col5 country_col8 /// 
        firmweightdomestic_col2 firmweightdomestic_col5 firmweightdomestic_col8, ///
        ycommon xsize(15) ysize(12) loff 
    graph export ${fig_dir}/appendix/Figure_A3_p_histograms_country_firmweightdom.pdf, replace
    graph export ${fig_dir}/appendix/Figure_A3_p_histograms_country_firmweightdom.eps, replace

}
if _rc == 0 {
    display "Execution finished successfully."
}
else {
    display "Execution finished with errors."
}

cap log close fig